package cn.edu.pku.controller;

import cn.edu.pku.service.CountInfoService;
import cn.edu.pku.service.UserInfoService;
import cn.edu.pku.vo.CountResult;
import cn.edu.pku.vo.LoginResult;
import cn.edu.pku.vo.LogoutResult;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * Created by ming.qin on 2017/4/20.
 */
@RestController
@Slf4j
public class Controller {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CountInfoService countInfoService;

    /**
     * 登录
     *
     * @param name
     * @param pass
     * @param session
     * @return
     */
    @RequestMapping(value = "/login")
    @ApiOperation(value = "用户登录接口", notes = "用户登录接口，传入用户名，密码")
    public LoginResult login(@RequestParam("name") String name, @RequestParam("pass") String pass, HttpSession session) {
        log.info("name = {},pass = {}", name, pass);
        LoginResult result = userInfoService.getByNamePass(name, pass);
        if (result.getToken() != null) {
            session.setAttribute("loginFlag", result.getToken());
            session.setAttribute(result.getToken(), result.getName());
        }
        log.info("LoginResult = {}", result);
        return result;
    }

    @RequestMapping(value = "/logout")
    @ApiOperation(value = "用户退出接口", notes = "")
    public LogoutResult logout(HttpSession session) {
        LogoutResult result = new LogoutResult();
        String token = (String) session.getAttribute("loginFlag");
        session.removeAttribute(token);
        session.removeAttribute("loginFlag");
        result.setStatus(200);
        return result;
    }

    @RequestMapping(value = "/indexCount", method = RequestMethod.GET)
    @ApiOperation(value = "首页统计信息", notes = "")
    public CountResult listCount() {
        CountResult result = new CountResult();
        result.setBookCount(countInfoService.selectBookInfoCount());
        result.setBookNoteCount(countInfoService.selectBookNoteCount());
        result.setData(countInfoService.selectCountInfo());
        return result;
    }

}
